package com.gtq.uhome.controller;

import com.gtq.uhome.service.IVerifyCodeService;
import com.gtq.uhome.util.MapUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author ylhy
 * @Describe
 * @create 2020-07-29 15:07
 */
@Controller
@ResponseBody
public class SendVerifyCodeController {
    @Resource
    MapUtil mapUtil;

    @Resource(name = "iVerifyCodeService")
    IVerifyCodeService iVerifyCodeService;



    /**
     * 发送验证码
     * @param phoneNumber
     * @return
     */
    @PostMapping(value = "/sendVerifyCode")
    @ResponseBody
    public void sendVerifyCode(@RequestParam("phoneNumber") String phoneNumber, HttpServletRequest request){
        System.out.println(phoneNumber);
        mapUtil.clear();
        int verifyCode = 0;
        try {
            verifyCode = this.iVerifyCodeService.sendVerifyCode(phoneNumber);
        } catch (Exception e) {

        }
        //创建session对象
        HttpSession session = request.getSession();
        //顺利发送后就直接将验证码存在session中
        if (verifyCode!=0) {
            session.setAttribute("verifyCode",verifyCode);
        }
    }

    @GetMapping(value = "/checkSendVerifyCode")
    public Map<String,Object> checkVerifyCode(@RequestParam("verifyCode") String verifyCode,
                                              HttpServletRequest request) {
        System.out.println(verifyCode);
        //找到之前创建session对象中的验证码的值 VerifyCode
        HttpSession session = request.getSession(false);
        Integer inputVerifyCode = (Integer) session.getAttribute("verifyCode");

        boolean result = (inputVerifyCode == Integer.valueOf(verifyCode)) ? true:false;
        mapUtil.clear();
        mapUtil.setCode("o");
        mapUtil.put("Result",result);

        return mapUtil.getValues();
    }

}
